<template>
  <div class="h-p100 w-p100">
    <div class="box box-ver h-p100 of-y-s">
      <transition :name="$store.state.routerAni">
        <router-view class="router-view"></router-view>
      </transition>
      <div class="tab-container box box-ac box-pc">
        <div class="tab-list box box-pc">
          <div @click="changeTag(index,'billStatus')" :value="item" :key="index" v-for="(item, index) in billStatus.list" :class="{act:index==billStatus.checkedIndex}" class="animated tab-item box box-ac box-pc box-f1 box-fh">{{item.name}}</div>
        </div>
      </div>
      <div class="business-container box">
        <div @click="changeTag(index,'businessType')" :value="item" :key="index" v-for="(item, index) in businessType.list" :class="{act:index==businessType.checkedIndex}" class="item box box-f1 box-ac box-pc box-ver">
          <div :class="'icon-business'+index" class="icon animated"></div>
          <div class="text">{{item.name}}</div>
        </div>
      </div>
      <div class="date-container box box-ac box-pc">
        <div @click="showPicker(0)" class="box datePicker box-ac">
          <div class="date">{{startDate}}</div>
        </div>
        <div class="split"></div>
        <div @click="showPicker(1)" class="box datePicker box-ac">
          <div class="date">{{endDate}}</div>
        </div>
      </div>
      <div ref="wrapper" class="box-f1 bill-container wrapper">
        <div class="content box box-ver">
          <no-data v-if="JSON.stringify(billList) == '{}'"></no-data>
          <div class="list box box-ver">
            <div :value="item" :key="index" v-for="(item,index) in billList" v-if="item.length>0" class="item box">
              <div class="left">{{index}}</div>
              <div class="right box box-f1 box-ver">
                <div :value="bill" :key="index1" v-for="(bill, index1) in item" class="bill-item box">
                  <div @tap="getInvoiceDetail(index,index1)" class="bill-content box box-f1 box-ver">
                    <div class="salesname ell">
                    {{bill.salesname}}&nbsp;
                    </div>
                    <div class="box">
                      <div class="money">¥{{bill.totalamount}}元</div>
                      <div class="date box-f1"></div>
                      <div class="date">{{bill.invoicedate}}</div>
                    </div>
                    <div class="status box box-ac">
                      <div v-if="bill.invoicetype == '04' || bill.invoicetype == '10'" class="icon icon-status icon-status1"></div>
                      <div v-if="bill.invoicetype == '01'" class="icon icon-status icon-status2"></div>
                      <div v-if="bill.invoicetype == '10'" class="icon icon-status icon-status3"></div>
                      <div v-if="bill.invoicetype == '04' || bill.invoicetype == '01'" class="icon icon-status icon-status4"></div>
                      <div v-if="bill.usestate == '1'" class="icon icon-status icon-status5"></div>
                      <div v-if="bill.usestate == '2'" class="icon icon-status icon-status6"></div>
                      <div v-if="bill.ckstatus == '1'" class="icon icon-status icon-status7"></div>
                      <div class="box-f1"></div>
                      <div v-if="bill.usestate != 1" @tap="deleteInvoice($event, index, index1)" class="del-container">
                        <div class="icon icon-status icon-del"></div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

</template>

<script>
import config from '@/js/config'
import Picker from '@/js/datePicker'
import BScroll from 'better-scroll'
import { getWeek, getMonth, getYear } from '@/js/common'
import { popup, openToast } from '@/js/tools'
import '../css/dataPicker.scss'
import noData from '@/components/noData'
import { mapState } from 'vuex'
export default {
  components: {
    noData
  },
  data () {
    return {
      billList: {
        '': []
      },
      startDate: '',
      endDate: '',
      pageNo: 0,
      businessType: {
        checkedIndex: 0,
        list: [{
          name: '全部',
          id: ''
        }, {
          name: '住宿费',
          id: 1
        }, {
          name: '餐饮费',
          id: 2
        }, {
          name: '通讯费',
          id: 3
        }, {
          name: '其他',
          id: 4
        }]
      },
      billStatus: {
        checkedIndex: 0,
        list: [{
          name: '未报销',
          id: 2
        }, {
          name: '已报销',
          id: 1
        }, {
          name: '全部',
          id: ''
        }]
      }
    }
  },
  computed: {
    ...mapState(['userNum'])
  },
  mounted () {
    let _this = this
    let Amethod = [getWeek, getMonth, getYear]
    let type = this.$route.query.type
    type = type ? +type : 2
    this.startDate = Amethod[+type]('s', 0)
    this.endDate = Amethod[+type]('e', 0)
    this.$nextTick(() => {
      if (!this.scroll) {
        _this.scroll = new BScroll(this.$refs.wrapper, {
          tap: true,
          pullUpLoad: {
            threshold: -50
          }
        })
        _this.scroll.on('pullingUp', (pos) => {
          _this.pageNo++
          _this.findListInvoice(_this.pageNo)
        })
        _this.findListInvoice(_this.pageNo)
      }
    })
  },
  beforeRouteLeave (to, from, next) {
    if (document.querySelector('.pop-container')) return
    let datePicker = document.querySelector('.zx_mask')
    if (datePicker) datePicker.remove()
    next()
  },
  methods: {
    showPicker (type) {
      let _this = this
      let defaultValue = type === 0 ? _this.startDate : _this.endDate
      let minYear = 2010
      let maxYear = 2030
      // if (type === 0) {
      //   maxYear = this.endDate
      // } else if (type === 1) {
      //   minYear = this.startDate
      // }
      let picker = new Picker({
        type: '3', // 0-年, 1-年月, 2-月日, 3-年月日
        title: '请选择日期', // 标题（可选）
        maxYear: maxYear, // 最大年份（可选）
        minYear: minYear, // 最小年份（可选）
        separator: '-', // 日期分割符(可选)
        defaultValue: defaultValue, // 默认值（可选）
        callBack: function (val) {
          if (type === 0) {
            _this.startDate = val
          } else {
            _this.endDate = val
          }
          _this.pageNo = 0
          _this.findListInvoice()
        }
      })
    },
    changeTag (index, data) {
      if (this[data].checkedIndex !== index) {
        this[data].checkedIndex = index
        this.pageNo = 0
        this.findListInvoice()
      }
    },
    findListInvoice () {
      let _this = this
      _this.$http({
        $vue: _this,
        type: 'XML',
        method: 'post',
        url: config.GXUrl + '/CheckInvoice/services/AutoImageCenter.ws?wsdl',
        data: {
          servername: 'FindListInvoice',
          data: {
            useraccount: _this.userNum,
            invoicecode: '',
            invoicenum: '',
            startdate: _this.startDate,
            enddate: _this.endDate,
            usestate: _this.billStatus.list[_this.billStatus.checkedIndex].id,
            pagesize: 20,
            invoicetype: '',
            detailedtype: _this.businessType.list[_this.businessType.checkedIndex].id,
            pageindex: _this.pageNo
          }
        }
      }).then(item => {
        _this.scroll.finishPullUp()
        if (+item.result['#text'] === 0) {
          let billList = []
          if (_this.pageNo === 0) {
            _this.billList = {}
          }
          if (!item.invoices) {
            billList = []
            // console.log('pageNo>>>>>', _this.pageNo)
            if (_this.pageNo !== 0) {
              openToast({
                msg: '暂无更多数据',
                duration: 1500
              })
            }
            _this.pageNo--
          } else {
            billList = [].concat(item.invoices.invoice)
          }
          let copyBillList = JSON.parse(JSON.stringify(_this.billList))
          billList.forEach((item, index) => {
            let invoicedate = item.invoicedate['#text'].substring(0, 7)
            if (!copyBillList[invoicedate]) {
              copyBillList[invoicedate] = []
            }
            let getVal = (obj, key) => {
              if (obj[key]) {
                return obj[key]['#text']
              } else {
                return ''
              }
            }
            copyBillList[invoicedate].push({
              invoicecode: getVal(item, 'invoicecode'),
              invoicenum: getVal(item, 'invoicenum'),
              invoicedate: getVal(item, 'invoicedate'),
              invoiceamount: getVal(item, 'invoiceamount'),
              totalamount: getVal(item, 'totalamount'),
              remark: getVal(item, 'remark'),
              ckstatus: getVal(item, 'ckstatus'),
              datasource: getVal(item, 'datasource'),
              usestate: getVal(item, 'usestate'),
              invoicetype: getVal(item, 'invoicetype'),
              buyername: getVal(item, 'buyername'),
              salesname: getVal(item, 'salesname'),
              checkcode: getVal(item, 'checkcode'),
              pdfuuid: getVal(item, 'pdfuuid'),
              filepath: getVal(item, 'filepath')
            })
          })
          _this.billList = copyBillList
          _this.$nextTick(() => {
            _this.scroll.refresh()
          })
        }
      })
    },
    deleteInvoice ($event, index, index1) {
      let _this = this
      let bill = _this.billList[index][index1]
      let invoicecode = bill.invoicecode
      let invoicenum = bill.invoicenum
      $event.stopPropagation()
      // console.log(bill.usestate)
      // if ((+bill.datasource !== 2) && (+bill.usestate === 2)) {
      // if (bill.datasource) {
      if ((+bill.usestate === 2)) {
        let msg = (+bill.datasource !== 2) ? '确定删除此发票？' : '微信卡包导入数据删除后无法再导入，确认删除？'
        popup({
          tpl: 'alert',
          title: '提示',
          content: msg,
          buttons: ['取消', '<div class="tc-main">确定</div>'],
          buttonCallBack: function (btnIndex) {
            if (btnIndex === 1) {
              _this.$http({
                $vue: _this,
                type: 'XML',
                method: 'post',
                url: config.GXUrl + '/CheckInvoice/services/AutoImageCenter.ws?wsdl',
                data: {
                  servername: 'DeleteInvoice',
                  data: {
                    useraccount: _this.userNum,
                    invoicecode,
                    invoicenum
                  }
                }
              }).then(item => {
                if (+item.result['#text'] === 0) {
                  _this.billList[index].splice(index1, 1)
                  // _this.$set(this.detailList[index], _this.billList[index].splice(index1, 1))
                  openToast({
                    msg: '删除成功',
                    duration: 1500
                  })
                }
              })
            }
          }
        })
      } else {
        openToast({
          msg: '无法删除',
          duration: 1500
        })
      }
    },
    getInvoiceDetail (index, index1) {
      this.$store.state.invoiceDetail = this.billList[index][index1]
      this.$router.push('/myInvoice/invoiceDetail')
    }
  }
}
</script>

<style lang="scss" scoped>
@import '../css/color';
@import '../css/mixins';
.router-view{
  z-index:3
}
.date-container{
  background-color:#FFF;
  // box-shadow: 0 .2rem .2rem 0 #ddd;
  // z-index:2;
  padding:.2rem 0;
  .split{
    width:.3rem;
    margin:.2rem;
    border-bottom:2px solid #efefef;
  }
  .datePicker{
    padding:.18rem;
    font-size:.28rem;
    border-radius:.1rem;
    background-color: #efefef;
  }

}
.tag-container{
  background-color:#FFF;
  padding:.25rem .3rem;
  box-shadow: 0 .1rem .1rem #ddd;
  z-index:2;
}
.tab-container{
  padding-top:.2rem;
  padding-bottom:.2rem;
  background-color:#FFF;
  .tab-list{
    $tabThemeColor:#6bb3ff;
    border-radius:.1rem;
    overflow: hidden;
    border:1px solid $tabThemeColor;
    width:4.8rem;
    .tab-item{
      height: 0.7rem;
      color:$tabThemeColor;
      font-size:.28rem;
      border-right:1px solid $tabThemeColor;
      &:last-child{
        border:none;
      }
      &.act{
        color:#FFF;
        background-color:#6bb3ff;
      }
    }
  }
}

.bill-container{
  overflow-y: hidden;
  width:100%;
}
.list{
  padding:.2rem;
  .item{
    .left{
      width:1.5rem;
      font-size:.26rem;
      color:#666;
    }
    .right{
      .bill-item{
        height: 1.9rem;
        border-left:1px solid $themeColor;
        padding-left:.35rem;
        padding-bottom:.2rem;
        &:before{
          position:absolute;
          content:'';
          top:0;
          left:-.12rem;
          width:.22rem;
          height: .22rem;
          border-radius:50%;
          background-color:$themeColor;
        }
        .bill-content{
          border-radius:.1rem;
          // border:1px solid $themeColor;
          padding:.2rem;
          color:#666;
          font-size:.3rem;
          font-size:.28rem;
          background-color:#FFF;
          text-decoration: none;
          .salesname{
            width:4.5rem;
            font-size:.3rem;
            padding-bottom:.28rem;
          }
          .date{
            color:#999;
            font-size:.26rem;
          }
          .money{
            color:#999;
            font-size:.26rem;
          }
          .status{
            margin-top:.2rem;
          }
          .icon-status{
            width:.3rem;
            height:.31rem;
            margin-top:.1rem;
            margin-bottom:.1rem;
            margin-right:.2rem;
          }
          .icon-status5,.icon-status6{
            width:.6rem;
            height:.3rem;
          }
          .icon-status7{
            width:.28rem;
            height:.33rem;
          }
          .del-container{
            padding-left:.1rem;
            padding-right:.1rem;
            .icon-del{
              margin:.1rem;
              @include bg-image('../img/icon-del');
            }
          }

          @for $i from 1 through 7 {
            .icon-status#{$i} {
              @include bg-image('../img/icon-status#{$i}');
            }
          }
        }
      }
    }
  }
}
</style>
